import asyncio
import logging

import ujson as ujson
from aiohttp import ClientSession, ServerTimeoutError


class HttpClient:

    def __init__(self):
        self.__client = ClientSession()

    async def close(self):
        await self.__client.close()
        self.__client = None

    async def request(self, method, url, parse_json=True, resp_content_type=None, encoding="", **kwargs):
        try:
            async with self.__client.request(method=method, url=url, **kwargs) as resp:
                if parse_json:
                    if resp.status in (200, 204):
                        res = await resp.json(loads=ujson.loads, content_type=resp_content_type)
                        return res
                if resp.status in (200, 204):
                    if encoding:
                        return await resp.text(encoding=encoding)
                    return await resp.read()
        except (asyncio.TimeoutError, ServerTimeoutError) as ex:
            logging.exception(ex)
        except Exception as ex:
            logging.exception(ex)

    async def get(self, url, parse_json=True, **kwargs):
        return await self.request('GET', url, parse_json=parse_json, **kwargs)

    async def post(self, url, parse_json=True, **kwargs):
        return await self.request('POST', url, parse_json=parse_json, **kwargs)
